<?php
/**
 * +--------------------------------------------------------+
 * @Created by PhpStorm.
 * @Category SwooleCommand.php
 * @Depiction:
 * Author: hwy
 * Date: 2020/6/3  10:30
 * +--------------------------------------------------------+
 */

namespace App\Console\Commands;

use Illuminate\Console\Command;

class SwooleCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'swoole {action}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '开启 swoole 服务';

    private $serv;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $arg = $this->argument('action');

        switch ($arg) {
            case 'start':
                $this->info('swoole observer started');
                $this->start();
                break;
            case 'stop':
                $this->info('stoped');
                break;
            case 'restart':
                $this->info('swoole observer restarted');
                $this->reload();
                break;
            default:
                $this->error("unknown command");
        }
    }

    private function start()
    {
        $this->serv = new \swoole_server("0.0.0.0", 9501);
        $this->serv->set(array(
            'worker_num'               => 6,
            'daemonize'                => true,
            'heartbeat_idle_time'      => 40,
            'heartbeat_check_interval' => 30,
            'buffer_output_size'       => 256 * 1024 * 1024, // 必须为数字
            'socket_buffer_size'       => 256 * 1024 * 1024,
            'open_eof_check'           => true, //打开EOF检测
            'package_eof'              => "\r\n\r\n\n\n\n0000", //设置EOF
            'open_eof_split'           => true,
        ) // 必须为数字
        // 'backlog' => 128,
        );

        $handler = App('App\Handlers\SwooleHandler');
        $this->serv->on('Start', array(
            $handler,
            'onStart'
        ));
        $this->serv->on('Connect', array(
            $handler,
            'onConnect'
        ));
        $this->serv->on('Receive', array(
            $handler,
            'onReceive'
        ));
        $this->serv->on('Close', array(
            $handler,
            'onClose'
        ));
        $this->serv->start();
    }

    private function reload()
    {
        $this->serv = new \swoole_server("0.0.0.0", 9501);
        $this->serv->reload();
//         \swoole_server::reload();
    }

}
